<!--
 *Author：jxx
 *Date：{Date}
 *Contact：283591387@qq.com
 *业务请在@/extension/co/co/ProductCosCalculate.jsx或ProductCosCalculate.vue文件编写
 *新版本支持vue或【表.jsx]文件编写业务,文档见:https://doc.volcore.xyz/docs/view-grid、https://doc.volcore.xyz/docs/web
 -->
<template>
    <div class="grid">
        <view-grid ref="grid" :columns="columns" :detail="detail" :details="details" :editFormFields="editFormFields"
            :editFormOptions="editFormOptions" :searchFormFields="searchFormFields" :searchFormOptions="searchFormOptions"
            :table="table" :extend="extend" :onInit="onInit" :onInited="onInited" :searchBefore="searchBefore"
            :searchAfter="searchAfter" :addBefore="addBefore" :updateBefore="updateBefore" :rowClick="rowClick"
            :modelOpenBefore="modelOpenBefore" :modelOpenAfter="modelOpenAfter" :spanMethod="spanMethod">
            <!-- 自定义组件数据槽扩展，更多数据槽slot见文档 -->
            <template #gridHeader>
            </template>
        </view-grid>
        <vol-box :lazy="true" v-model="model1" title="成本计算单" :width="700" :height="200" :padding="5">
            <div class="container">
                <div class="content">
                    <vol-form ref="form" :loadKey="true" :formFields="formFields" :formRules="formRules"
                        labelPosition='left' ,>
                        <div style="text-align: center; width: 100%; margin-top: 30px">
                            <el-steps style="max-width: 700px;" :active="isActive" process-status="wait"
                                finish-status="success" simple>
                                <el-step title="产成品入库归集" />
                                <el-step title="原材料成本归集" />
                                <el-step title="原材料成本分配" />
                            </el-steps>
                        </div>
                    </vol-form>
                    <div style="text-align: center; width: 100%; margin-top: 10px">
                        <el-button type="primary" @click="beginProductCostCalaulate">开始</el-button>
                        <el-button type="info" plain @click="closeBtn">关闭</el-button>
                    </div>
                </div>
            </div>
        </vol-box>
    </div>
</template>
<script setup lang="jsx">
import extend from "@/extension/co/co/ProductCosCalculate.jsx";
import viewOptions from './ProductCosCalculate/options.js'
import { ElLoading } from 'element-plus'
import { ref, reactive, getCurrentInstance, watch, onMounted } from "vue";
const grid = ref(null);
const { proxy } = getCurrentInstance()
//http请求，proxy.http.post/get
const { table, editFormFields, editFormOptions, searchFormFields, searchFormOptions, columns, detail, details } = reactive(viewOptions())
const isActive = ref(0)
const model1 = ref(false)

let gridRef;//对应[表.jsx]文件中this.使用方式一样
//生成对象属性初始化
const onInit = async ($vm) => {
    gridRef = $vm;
    gridRef.pagination.sortName = "ProductCosCalculateId";  //设置排序字段,多个字段排序用逗号隔开,如:a,b,c
    gridRef.pagination.order = "asc"; //排序方式desc或者asc
    columns.forEach((x) => {
        if (x.field == 'PeriodYear' || x.field == 'PeriodMonth' || x.field == 'DepartmentId'
            || x.field == 'MaterialId'
            || x.field == 'MaterialName'
            || x.field == 'Spec'
            || x.field == 'ProductTaskId'
        ) {
            x.class = 'col-test'
        }
    });
}
//生成对象属性初始化后,操作明细表配置用到
const onInited = async () => {

    gridRef.buttons.splice(3, 0, {
        name: '成本计算', //按钮名称
        icon: 'el-icon-document',
        type: 'primary',
        plain: true,
        onClick: () => {
            isActive.value = 0
            model1.value = true
        }
    })
    gridRef.buttons.splice(4, 0, {
        name: '期末结账', //按钮名称
        icon: 'el-icon-document',
        type: 'primary',
        plain: true,
        onClick: () => {
            endPeriodSettlement()
        }
    })
    gridRef.buttons.splice(4, 0, {
        name: '反结账', //按钮名称
        icon: 'el-icon-document',
        type: 'primary',
        plain: true,
        onClick: () => {
            unEndPeriodSettlement()
        }
    })
}
const beginProductCostCalaulate = async () => {
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })

    let url = 'api/ProductCosCalculate/costCalculate';
    proxy.http.post(url).then((result) => {
        gridRef.search();
        setTimeout(() => {
            isActive.value = 1
            isActive.value = 2
            setTimeout(() => {
                loading.close()
                isActive.value = 3
                proxy.$message.success("产成品计算完成");
            }, 1000)

        }, 2000)

    });

}

const endPeriodSettlement = async () => {

    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })

    let url = 'api/ProductCosCalculate/endPeriodSettlement';
    proxy.http.post(url).then((result) => {
        gridRef.search();
        setTimeout(() => {
            setTimeout(() => {
                loading.close()
                proxy.$message.success("结账成功！");
            }, 1000)

        }, 2000)

    });

}
const unEndPeriodSettlement = async () => {

    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })

    let url = 'api/ProductCosCalculate/unEndPeriodSettlement';
    proxy.http.post(url).then((result) => {
        gridRef.search();
        setTimeout(() => {
            setTimeout(() => {
                loading.close()
                proxy.$message.success("反结账成功！");
            }, 1000)

        }, 2000)

    });

}
const closeBtn = async () => {
    model1.value = false

}
const searchBefore = async (param) => {
    //界面查询前,可以给param.wheres添加查询参数
    //返回false，则不会执行查询
    return true;
}
const searchAfter = async (rows, result) => {
    return true;
}
const addBefore = async (formData) => {
    //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
    return true;
}
const updateBefore = async (formData) => {
    //编辑保存前formData为对象，包括明细表、删除行的Id
    return true;
}
const rowClick = ({ row, column, event }) => {
    //查询界面点击行事件
    // grid.value.toggleRowSelection(row); //单击行时选中当前行;
}
const modelOpenBefore = async (row) => {//弹出框打开后方法
    return true;//返回false，不会打开弹出框
}
const modelOpenAfter = (row) => {
    //弹出框打开后方法,设置表单默认值,按钮操作等
}
const spanMethod = ({ row, column, rowIndex, columnIndex }, rows) => {
    // 假设要合并第1列(columnIndex === 1)

    // 获取当前列的字段名
    const productTaskField = gridRef.columns[7].field
    const specField = gridRef.columns[6].field
    if (columnIndex === 1 || columnIndex === 2 || columnIndex === 3 || columnIndex === 4 || columnIndex === 5 || columnIndex === 6 || columnIndex === 7) {

        const field = gridRef.columns[columnIndex].field

        // 如果是第一行，从这一行开始统计
        if (rowIndex === 0) {
            let count = 1 // 记录相同值的数量
            // 向下查找相同值的行数
            for (let i = 1; i < rows.length; i++) {
                if (rows[i][field] === row[field] && rows[i][productTaskField] === row[productTaskField]) {
                    count++
                } else {
                    break
                }
            }
            // 返回要合并的行数
            return {
                rowspan: count,
                colspan: 1
            }
        } else {
            // 检查当前行的值是否与上一行相同
            const prevRow = rows[rowIndex - 1]
            if (prevRow && row[field] === prevRow[field] && row[productTaskField] === prevRow[productTaskField]) {
                // 如果与上一行相同，则不显示
                return {
                    rowspan: 0,
                    colspan: 0
                }
            }
            // 如果与上一行不同，需要计算向下合并的行数
            let count = 1
            for (let i = rowIndex + 1; i < rows.length; i++) {
                if (rows[i][field] === row[field] && rows[i][productTaskField] === row[productTaskField]) {
                    count++
                } else {
                    break
                }
            }
            return {
                rowspan: count,
                colspan: 1
            }
        }
    }
}
//监听表单输入，做实时计算
//watch(() => editFormFields.字段,(newValue, oldValue) => {	})
//对外暴露数据
defineExpose({})
</script>
<style scoped>
.td {
    vertical-align: top;
}
</style>
